import {
  ds
} from "../../../tools/data"
import {
  ui
} from "../../../tools/ui"
import {
  nav2
} from "../../../tools/nav2"
import {
  pages
} from "~/tools/pages";

Page({
  data: {
    list: [],
    locText: "",
    loc: [],
    errMsg: "",
    stepFee: 0,
    selectedShop: 0,
  },
  async init() {
    const that = this,
      _ = ds.cmd
    ds.coll('module')
      .where({
        _id: _.exists(true)
      })
      .orderBy('pos', 'asc')
      .get({
        success: function (res) {
          that.setData({
            list: res.data
          })
        }
      });
  },
  editMod(e) {
    const mod = ui.eventData(e, 'mod');
    nav2.navigate(`/pages/usercenter/module/${mod.type}/index?id=${mod._id}`);
  },
  backTap() {
    pages.back()
  },
  addModule(e) {
    ui.actionSheetx([{
      name: "轮播组件",
      value: "swiper"
    }, {
      name: "分栏组件",
      value: "column"
    }, {
      name: "消息组件",
      value: "msg"
    }, {
      name: "弹窗组件",
      value: "popup"
    }], res => {
      ui.loading()
      const maxPos = this.data.list?.reduce((r, ele) => Math.max(r, ele.pos), 0) || 0
      ds.cloudUpdate('module', undefined, {
        type: res.value,
        visible: true,
        pos: res.value == 'popup' ? 0 : (maxPos + 1)
      }, res => {
        ui.loading(false)
        const success = res.result.errMsg.endsWith(":ok")
        success && this.init()
      })
    })
  },
  changeVisible(e) {
    const mod = ui.eventData(e, "mod")
    ui.loading()
    const visible = (typeof mod.visible == 'undefined') ? false : !mod.visible
    ds.cloudUpdate('module', mod._id, {
      visible
    }, res => {
      ui.loading(false);
      const success = res.result.errMsg.endsWith(":ok")
      ui.toast(success)
      if (success) this.init()
    })
  },
  onShow() {},
  onLoad() {
    this.init(true);
  },
  onDelete(e) {
    const mod = ui.eventData(e, 'mod')
    ui.confirmx(`是否删除？`).then(res => {
      if (!res) return;
      ui.loading()
      ds.cloudRemove('module', {
        _id: mod.id || mod._id
      }, res => {
        const succ = res.result.errMsg.endsWith(":ok")
        ui.loading(false)
        ui.toast(succ)
        succ && this.init()
      })
    })
  }
});